import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode';
import { Avatar, Typography, Card, Progress, Button, Modal, Tag, Spin, ConfigProvider, theme, message } from 'antd';
import { UserOutlined, DollarOutlined, WechatOutlined } from '@ant-design/icons';
import './RechargeModal.css';
import { useQuery } from '@tanstack/react-query';
import { User } from '@/types/api';
import { RechargeOption } from '@/components/PointsCenter/types';
import { getCurrentUser, isAuthenticated, getMyPoints, PointsMeData, createPaymentOrder, PaymentOrderData, queryPaymentStatus, PaymentStatusResponse } from '@/services/api';
import { useNavigate } from 'react-router-dom';
import './UserUsageProfile.css';

const { Title, Text } = Typography;

// 暗黑主题配置
const darkTheme = {
    algorithm: theme.darkAlgorithm,
    token: {
        colorPrimary: '#1890ff',
        colorBgContainer: '#1f1f1f',
        colorBgElevated: '#2a2a2a',
        colorText: '#ffffff',
        colorTextSecondary: 'rgba(255, 255, 255, 0.85)',
        colorTextTertiary: 'rgba(255, 255, 255, 0.65)',
        colorBorder: '#434343',
        colorBorderSecondary: '#434343',
        borderRadius: 8,
        colorFillSecondary: '#434343',
    },
    components: {
        Modal: {
            colorBgElevated: '#2a2a2a',
            colorText: '#ffffff',
            colorTextHeading: '#ffffff',
            colorBgMask: 'rgba(0, 0, 0, 0.8)',
        },
        Button: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorPrimary: '#1890ff',
            colorPrimaryHover: '#40a9ff',
            colorPrimaryActive: '#096dd9',
        },
        Typography: {
            colorText: '#ffffff',
            colorTextSecondary: 'rgba(255, 255, 255, 0.85)',
            colorTextTertiary: 'rgba(255, 255, 255, 0.65)',
        },
        Spin: {
            colorPrimary: '#1890ff',
        },
    },
};

// 模拟数据 - 充值选项（匹配图片中的选项）
const RECHARGE_OPTIONS: RechargeOption[] = [
    { amount: 99, bonus: 0, label: '99积分', price: 9.9, description: '9.9元' },
    { amount: 200, bonus: 0, label: '200积分', price: 20, description: '20元' },
    { amount: 600, bonus: 0, label: '600积分', price: 60, description: '60元' },
    { amount: 1000, bonus: 0, label: '1000积分', price: 100, description: '100元' },
];

// 支付方式类型
type PaymentMethod = 'wechat' | null;

// 使用真实接口数据，移除模拟数据

const UserUsageProfile: React.FC = () => {
    const navigate = useNavigate();
    const [selectedRechargeOption, setSelectedRechargeOption] = useState<RechargeOption | null>(null);
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<PaymentMethod>(null);
    const [isRechargeModalVisible, setIsRechargeModalVisible] = useState(false);
    // 实时积分数据
    const { data: pointsData, isLoading: isLoadingPoints } = useQuery<PointsMeData>({
        queryKey: ['points-me'],
        queryFn: getMyPoints,
        enabled: isAuthenticated(),
        staleTime: 0,
        gcTime: 0,
        refetchOnMount: true,
        refetchOnWindowFocus: true,
    });
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [customAmount, setCustomAmount] = useState<string>('');
    const itemsPerPage = 10;

    // 支付相关状态
    const [paymentOrder, setPaymentOrder] = useState<PaymentOrderData | null>(null);
    const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
    const [isGeneratingQR, setIsGeneratingQR] = useState<boolean>(false);
    const [isPaymentModalVisible, setIsPaymentModalVisible] = useState<boolean>(false);
    const [paymentStatus, setPaymentStatus] = useState<PaymentStatusResponse['data'] | null>(null);
    const [isPolling, setIsPolling] = useState<boolean>(false);
    const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(null);

    // 获取当前用户信息
    const { data: currentUser, isLoading } = useQuery<User>({
        queryKey: ['current-user'],
        queryFn: getCurrentUser,
        enabled: isAuthenticated(),
        staleTime: 5 * 60 * 1000,
    });
    // 停止轮询
    const stopPolling = () => {
        if (pollingInterval) {
            clearInterval(pollingInterval);
            setPollingInterval(null);
        }
        setIsPolling(false);
    };
    // 组件卸载时清理轮询
    useEffect(() => {
        return () => {
            stopPolling();
        };
    }, []);

    // 自动设置微信支付为默认选择
    useEffect(() => {
        if (isRechargeModalVisible && !selectedPaymentMethod) {
            setSelectedPaymentMethod('wechat');
        }
    }, [isRechargeModalVisible, selectedPaymentMethod]);

    if (!isAuthenticated()) {
        navigate('/login');
        return null;
    }

    if (isLoading || isLoadingPoints || !currentUser || !pointsData) {
        return (
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: '50vh',
                    color: 'white',
                }}
            >
                加载中...
            </div>
        );
    }

    // 处理充值
    const handleRecharge = async () => {
        if (!selectedRechargeOption && !customAmount) {
            Modal.warning({ title: '提示', content: '请选择充值金额' });
            return;
        }

        if (!selectedPaymentMethod) {
            Modal.warning({ title: '提示', content: '请选择支付方式' });
            return;
        }

        try {
            const amount = selectedRechargeOption?.amount || parseInt(customAmount);
            const amountInCents = amount * 10; // 转换为分

            setIsGeneratingQR(true);
            const order = await createPaymentOrder({
                amount: amountInCents,
                description: `积分充值 - ${amount}积分`,
            });

            setPaymentOrder(order);
            setIsRechargeModalVisible(false);
            setIsPaymentModalVisible(true);

            // 生成二维码
            const qrCodeDataURL = await QRCode.toDataURL(order.code_url, {
                width: 256,
                margin: 2,
                color: {
                    dark: '#000000',
                    light: '#FFFFFF',
                },
            });

            setQrCodeUrl(qrCodeDataURL);

            // 开始轮询支付状态
            startPollingPaymentStatus(order.out_trade_no);
        } catch (error: any) {
            Modal.error({
                title: '创建支付订单失败',
                content: error.message || '请稍后重试',
            });
        } finally {
            setIsGeneratingQR(false);
        }
    };

    // 计算实际支付金额
    const calculatePaymentAmount = () => {
        if (selectedRechargeOption) {
            return selectedRechargeOption.price || selectedRechargeOption.amount * 0.1;
        }
        return customAmount ? parseFloat(customAmount) * 0.1 : 0;
    };

    // 轮询支付状态
    const startPollingPaymentStatus = (outTradeNo: string) => {
        if (pollingInterval) {
            clearInterval(pollingInterval);
        }

        setIsPolling(true);
        const interval = setInterval(async () => {
            try {
                const response = await queryPaymentStatus(outTradeNo);
                setPaymentStatus(response);
                if (response.status === 'SUCCESS') {
                    // 支付成功，停止轮询
                    clearInterval(interval);
                    setIsPolling(false);
                    setPollingInterval(null);
                    message.success('支付成功,2秒后刷新积分数据');
                    // 刷新积分数据
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else if (response.status === 'FAILED' || response.status === 'CANCELLED') {
                    // 支付失败或取消，停止轮询
                    clearInterval(interval);
                    setIsPolling(false);
                    setPollingInterval(null);
                }
            } catch (error) {
                console.error('查询支付状态失败:', error);
            }
        }, 750);

        setPollingInterval(interval);
    };

    // 关闭支付模态框
    const handleClosePaymentModal = () => {
        stopPolling();
        setIsPaymentModalVisible(false);
        setPaymentOrder(null);
        setQrCodeUrl('');
        setPaymentStatus(null);
        setSelectedRechargeOption(null);
        setSelectedPaymentMethod(null);
        setCustomAmount('');
    };

    // 计算获得的积分
    const calculatePoints = () => {
        if (selectedRechargeOption) {
            return selectedRechargeOption.amount + (selectedRechargeOption.bonus || 0);
        }
        return customAmount ? parseInt(customAmount) : 0;
    };

    return (
        <div className="user-usage-profile">
            <div className="profile-container-800">
                {/* 用户信息和头像 */}
                <div className="user-info-section">
                    <div className="user-avatar-container">
                        <Avatar
                            size={80}
                            style={{
                                backgroundColor: currentUser.is_active ? '#87d068' : '#ff4d4f',
                            }}
                            icon={<UserOutlined />}
                        />
                        <div className="user-details">
                            <Title level={4} style={{ margin: 0 }}>
                                {currentUser.username}
                            </Title>
                            <Text type="secondary">@{currentUser.username}</Text>
                            <br />
                            <Text type="secondary">{currentUser.email}</Text>
                            <Tag style={{ marginLeft: 7 }} color={currentUser.is_active ? 'green' : 'red'}>
                                {currentUser.is_active ? '账户正常' : '账户禁用'}
                            </Tag>
                        </div>
                    </div>
                </div>

                {/* 积分使用情况卡片 */}
                <Card className="points-usage-card">
                    <div className="card-header">
                        <div className="header-left">
                            <DollarOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            <Text strong style={{ fontSize: 16 }}>
                                积分资产
                            </Text>
                        </div>
                    </div>

                    <div className="points-usage-content">
                        <Progress
                            percent={(pointsData as PointsMeData).gained_points > 0 ? Math.round(((pointsData as PointsMeData).balance / (pointsData as PointsMeData).gained_points) * 100 * 100) / 100 : 0}
                            status="active"
                            strokeColor="#6F01CF"
                            size={['100%', 10]}
                        />
                        <div className="points-usage-info">
                            <Text strong>
                                {(pointsData as PointsMeData).balance} / {(pointsData as PointsMeData).gained_points}
                            </Text>
                            <Text type="secondary">已使用 {(pointsData as PointsMeData).used_points}</Text>
                        </div>
                    </div>

                    <div className="points-usage-actions">
                        <Button type="primary" onClick={() => setIsRechargeModalVisible(true)}>
                            积分充值
                        </Button>
                    </div>
                </Card>

                {/* 其他积分使用情况卡片 */}
                <Card className="other-usage-card">
                    <div className="card-header">
                        <div className="header-left">
                            <Text strong style={{ fontSize: 16 }}>
                                积分变动
                            </Text>
                        </div>
                    </div>
                    {/* 积分变动记录表格 */}
                    <div className="usage-events-table">
                        <div className="table-header">
                            <div className="table-cell time-cell">时间</div>
                            <div className="table-cell">类型</div>
                            <div className="table-cell">变动积分</div>
                            <div className="table-cell">原因</div>
                            <div className="table-cell">关联草稿ID</div>
                            <div className="table-cell">变动后余额</div>
                        </div>

                        <div className="table-body">
                            {(pointsData as PointsMeData).history.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage).map((h: any) => (
                                <div key={h.id} className="table-row">
                                    <div className="table-cell time-cell">{new Date(h.created_at).toLocaleString()}</div>
                                    <div className="table-cell">
                                        <Tag color={h.type === 'increase' ? 'green' : 'red'}>{h.type === 'increase' ? '增加' : '减少'}</Tag>
                                    </div>
                                    <div className="table-cell">{h.type === 'increase' ? `+${h.amount}` : `-${h.amount}`}</div>
                                    <div className="table-cell">{h.reason}</div>
                                    <div className="table-cell">{h.draft_id || '-'}</div>
                                    <div className="table-cell">{h.balance_after}</div>
                                </div>
                            ))}
                        </div>

                        {/* 分页 */}
                        <div className="pagination">
                            <Button size="small" disabled={currentPage === 1} onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}>
                                ‹
                            </Button>

                            {Array.from({ length: Math.ceil((pointsData as PointsMeData).history.length / itemsPerPage) }, (_, i) => i + 1)
                                .filter((page) => page === 1 || page === Math.ceil((pointsData as PointsMeData).history.length / itemsPerPage) || (page >= currentPage - 1 && page <= currentPage + 1))
                                .map((page, index, pages) => {
                                    // 处理省略号
                                    if (index > 0 && pages[index - 1] !== page - 1) {
                                        return (
                                            <Button key={`ellipsis-${index}`} size="small">
                                                ...
                                            </Button>
                                        );
                                    }

                                    return (
                                        <Button key={page} size="small" className={`page-btn ${currentPage === page ? 'active' : ''}`} onClick={() => setCurrentPage(page)}>
                                            {page}
                                        </Button>
                                    );
                                })}

                            <Button
                                size="small"
                                disabled={currentPage === Math.ceil((pointsData as PointsMeData).history.length / itemsPerPage)}
                                onClick={() => setCurrentPage((prev) => Math.min(prev + 1, Math.ceil((pointsData as PointsMeData).history.length / itemsPerPage)))}
                            >
                                ›
                            </Button>
                        </div>
                    </div>
                </Card>

                {/* 充值模态框 - 高级黑暗风格 */}
                <Modal
                    title="积分充值"
                    open={isRechargeModalVisible}
                    onOk={handleRecharge}
                    onCancel={() => {
                        setIsRechargeModalVisible(false);
                        setSelectedRechargeOption(null);
                        setSelectedPaymentMethod(null);
                        setCustomAmount('');
                    }}
                    okText="去支付"
                    cancelText="取消"
                    width={700}
                    className="dark-recharge-modal"
                >
                    <div className="recharge-content">
                        {/* 左侧说明信息 */}
                        <div className="recharge-info">
                            <div className="recharge-info-header">
                                <Text className="recharge-info-title">积分</Text>
                            </div>
                            <div className="recharge-info-detail">
                                <Text className="recharge-info-balance">当前积分: {(pointsData as PointsMeData).balance}</Text>
                                <Text className="recharge-info-rate">10积分/元</Text>
                            </div>
                            <div className="recharge-info-rules">
                                <Text className="recharge-info-rule-item">• 积分可用于使用购买视频素材模板</Text>
                                <Text className="recharge-info-rule-item">• 积分为本系统虚拟服务，不可用</Text>
                                <Text className="recharge-info-rule-item">于平台外服务，请谨慎充值。</Text>
                            </div>
                            <div className="recharge-info-contact">
                                <Text
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.85)',
                                        fontSize: '14px',
                                        marginBottom: '12px',
                                        display: 'block',
                                        textAlign: 'center',
                                    }}
                                >
                                    如有疑问 请联系客服
                                </Text>
                                <img
                                    src="/qr.png"
                                    alt="联系客服二维码"
                                    style={{
                                        width: '200px',
                                        height: '200px',
                                        objectFit: 'contain',
                                        borderRadius: '8px',
                                        border: '1px solid rgba(255, 255, 255, 0.2)',
                                    }}
                                />
                            </div>
                        </div>

                        {/* 右侧充值选项 */}
                        <div className="recharge-options">
                            <div className="recharge-account">
                                <Text className="recharge-account-label">充值账号: {currentUser.username}</Text>
                            </div>

                            {/* 预设充值选项 */}
                            <div className="recharge-options-grid">
                                {RECHARGE_OPTIONS.map((option) => (
                                    <div
                                        key={option.amount}
                                        className={`recharge-option-card ${selectedRechargeOption?.amount === option.amount ? 'selected' : ''}`}
                                        onClick={() => {
                                            setSelectedRechargeOption(option);
                                            setCustomAmount('');
                                        }}
                                    >
                                        <div className="recharge-option-star">★</div>
                                        <div className="recharge-option-amount">{option.label}</div>
                                        <div className="recharge-option-price">{option.description}</div>
                                    </div>
                                ))}
                            </div>

                            {/* 其他数量积分 */}
                            <div className="recharge-custom">
                                <div className="recharge-custom-label">其他数量积分</div>
                                <div className="recharge-custom-input-wrapper">
                                    <input
                                        type="number"
                                        className="recharge-custom-input"
                                        value={customAmount}
                                        onChange={(e) => {
                                            setCustomAmount(e.target.value);
                                            setSelectedRechargeOption(null);
                                        }}
                                        placeholder="请输入积分数量"
                                        min="9.9"
                                        step="0.1"
                                    />
                                    <span className="recharge-custom-unit">积分</span>
                                </div>
                            </div>

                            {/* 支付方式 */}
                            <div className="recharge-payment">
                                <div className="recharge-payment-label">支付方式:</div>
                                <div className="recharge-payment-methods">
                                    <div className="recharge-payment-method selected" onClick={() => setSelectedPaymentMethod('wechat')}>
                                        <div className="recharge-payment-icon">
                                            <WechatOutlined style={{ color: '#07C160' }} />
                                        </div>
                                        <div className="recharge-payment-text">微信支付</div>
                                    </div>
                                </div>
                            </div>

                            {/* 支付信息 */}
                            <div className="recharge-summary">
                                {!selectedRechargeOption && !customAmount ? (
                                    <div className="recharge-summary-placeholder">
                                        <Text className="recharge-summary-placeholder-text">请选择充值金额</Text>
                                    </div>
                                ) : (
                                    <div className="recharge-summary-content">
                                        <div className="recharge-summary-info">
                                            <Text className="recharge-summary-label">实付: </Text>
                                            <Text className="recharge-summary-price">¥{calculatePaymentAmount().toFixed(1)}</Text>
                                            <Text className="recharge-summary-points">(获得 {calculatePoints()} 积分)</Text>
                                        </div>
                                    </div>
                                )}
                                <Text className="recharge-minimum">最小充值金额为9.9元 (约99积分)</Text>
                            </div>
                        </div>
                    </div>
                </Modal>

                {/* 微信支付模态框 */}
                <ConfigProvider theme={darkTheme}>
                    <Modal
                        title="微信支付"
                        open={isPaymentModalVisible}
                        onCancel={handleClosePaymentModal}
                        footer={[
                            <Button key="cancel" onClick={handleClosePaymentModal}>
                                取消支付
                            </Button>,
                            <Button key="refresh" type="primary" onClick={() => window.location.reload()}>
                                支付完成
                            </Button>,
                        ]}
                        width={400}
                        className="dark-recharge-modal"
                    >
                        <div className="payment-modal-content">
                            {paymentStatus?.status === 'SUCCESS' ? (
                                // 支付成功状态
                                <div className="payment-success">
                                    <div className="payment-success-icon">✅</div>
                                    <div className="payment-title">
                                        <Text strong className="payment-success-title">
                                            支付成功！
                                        </Text>
                                    </div>
                                    <div className="payment-success-info">
                                        <Text type="secondary">支付金额：¥{paymentOrder?.amount_yuan || 0}</Text>
                                        <Text type="secondary">交易号：{paymentStatus.transaction_id}</Text>
                                        <Text type="secondary">支付时间：{paymentStatus.paid_at ? new Date(paymentStatus.paid_at).toLocaleString() : '-'}</Text>
                                    </div>
                                </div>
                            ) : (
                                // 支付中状态
                                <>
                                    <div className="payment-title">
                                        <Text strong className="payment-title-text">
                                            {isPolling ? '正在查询支付状态...' : '请使用微信扫描二维码完成支付'}
                                        </Text>
                                    </div>

                                    {isGeneratingQR ? (
                                        <div className="payment-loading">
                                            <Spin size="large" />
                                            <div className="payment-loading-text">
                                                <Text>正在生成支付二维码...</Text>
                                            </div>
                                        </div>
                                    ) : qrCodeUrl ? (
                                        <div className="payment-qr-container">
                                            <img src={qrCodeUrl} alt="微信支付二维码" className="payment-qr-image" />
                                            <div className="payment-amount">
                                                <Text type="secondary">支付金额：¥{paymentOrder?.amount_yuan || 0}</Text>
                                            </div>
                                            <div className="payment-order">
                                                <Text type="secondary" className="payment-order-text">
                                                    订单号：{paymentOrder?.out_trade_no}
                                                </Text>
                                            </div>
                                            {isPolling && (
                                                <div className="payment-status">
                                                    <Spin size="small" />
                                                    <Text type="secondary" style={{ marginLeft: 8 }}>
                                                        等待支付完成...
                                                    </Text>
                                                </div>
                                            )}
                                        </div>
                                    ) : (
                                        <div className="payment-error">
                                            <Text type="secondary">二维码生成失败，请重试</Text>
                                        </div>
                                    )}
                                </>
                            )}
                        </div>
                    </Modal>
                </ConfigProvider>
            </div>
        </div>
    );
};

export default UserUsageProfile;
